//
//  VoucherDetailSheet.swift
//  CMB250716
//
//  Created by Assistant on 2025-01-11.
//

import SwiftUI
import Foundation

struct VoucherDetailSheet: View {
    @Environment(\.dismiss) private var dismiss
    @EnvironmentObject var dataManager: DataManager
    @State private var navigateToCart = false
    @State private var showingClearCartAlert = false
    @State private var showingLoginAlert = false
    @State private var showingLoginView = false
    
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                // 整个背景设为黑色
                Color.black
                
                VStack {
                    ZStack {
                    // 渐变背景：黑金黄、紫黑、金色混合
                    LinearGradient(
                        colors: [
                            Color.black,
                            Color(red: 0.2, green: 0.1, blue: 0.4), // 紫黑色
                            Color(red: 0.8, green: 0.6, blue: 0.0), // 金色
                            Color(red: 1.0, green: 0.8, blue: 0.2), // 黄金色
                            Color.black
                        ],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                    .clipShape(UnevenRoundedRectangle(topLeadingRadius: 20, topTrailingRadius: 20))
                
                    VStack(spacing: 0) {
                        // 返回按钮
                        HStack {
                            Button(action: {
                                dismiss()
                            }) {
                                Image(systemName: "chevron.left")
                                    .font(.system(size: 18, weight: .semibold))
                                    .foregroundColor(.white)
                                    .frame(width: 32, height: 32)
                                    .background(
                                        RoundedRectangle(cornerRadius: 8)
                                            .fill(Color.black.opacity(0.6))
                                            .overlay(
                                                RoundedRectangle(cornerRadius: 8)
                                                    .stroke(Color.white.opacity(0.3), lineWidth: 1)
                                            )
                                    )
                                    .shadow(color: Color.black.opacity(0.3), radius: 4, x: 0, y: 2)
                            }
                            .padding(.leading, 20)
                            .padding(.top, 15)
                            
                            Spacer()
                        }
                        
                        ScrollView {
                            VStack(spacing: 8) {
                                // 顶部标题区域
                                headerSection
                                
                                // 礼券表格
                                voucherTableSection
                                
                                // 使用条件
                                conditionsSection
                                
                                // Buy Now 按键 - 移动到Terms & Conditions上方并居中
                                HStack {
                                    Spacer()
                                    Button(action: {
                                        handleBuyNowTap()
                                    }) {
                                        Text(dataManager.currentLanguage == "zh" ? "立即购买" : "Buy Now")
                                            .font(.system(size: 16, weight: .bold))
                                            .foregroundColor(.white)
                                            .padding(.horizontal, 24)
                                            .padding(.vertical, 12)
                                            .background(
                                                LinearGradient(
                                                    colors: [
                                                        Color(red: 1.0, green: 0.4, blue: 0.0),
                                                        Color(red: 0.8, green: 0.3, blue: 0.0)
                                                    ],
                                                    startPoint: .top,
                                                    endPoint: .bottom
                                                )
                                            )
                                            .cornerRadius(25)
                                            .shadow(color: Color.orange.opacity(0.5), radius: 8, x: 0, y: 4)
                                    }
                                    Spacer()
                                }
                                .padding(.top, 8)
                                
                                // 条款说明
                                termsSection
                            }
                            .padding(.horizontal, 20)
                            .padding(.bottom, 20)
                        }
                    }
                    }
                }
            }
        }
        .ignoresSafeArea()
        .onChange(of: navigateToCart) { newValue in
            if newValue {
                NotificationCenter.default.post(
                    name: NSNotification.Name("NavigateToCart"),
                    object: nil
                )
            }
        }
        .alert(
            dataManager.currentLanguage == "zh" ? "清空购物车" : "Clear Cart",
            isPresented: $showingClearCartAlert
        ) {
            Button(
                dataManager.currentLanguage == "zh" ? "清空并购买" : "Clear & Buy",
                role: .destructive
            ) {
                // 清空购物车
                dataManager.clearCart()
                
                // 创建现金券套餐菜单项
                let voucherMenuItem = createVoucherPackageMenuItem()
                
                // 添加到购物车
                dataManager.addToCart(voucherMenuItem, quantity: 1)
                
                // 关闭当前页面
                dismiss()
                
                // 延迟后触发导航到购物车
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    navigateToCart = true
                }
            }
            
            Button(
                dataManager.currentLanguage == "zh" ? "取消" : "Cancel",
                role: .cancel
            ) { }
        } message: {
            Text(
                dataManager.currentLanguage == "zh" ? 
                "Cash Voucher 购买需单独购买，请先清空购物车。" : 
                "Cash Voucher must be purchased separately. Please clear your cart first."
            )
        }
        .alert(
            dataManager.currentLanguage == "zh" ? "需要登录" : "Login Required",
            isPresented: $showingLoginAlert
        ) {
            Button(
                dataManager.currentLanguage == "zh" ? "去登录" : "Login",
                role: .none
            ) {
                showingLoginView = true
            }
            
            Button(
                dataManager.currentLanguage == "zh" ? "取消" : "Cancel",
                role: .cancel
            ) { }
        } message: {
            Text(
                dataManager.currentLanguage == "zh" ? 
                "购买现金券套餐需要先登录账户。" : 
                "Please login to purchase Cash Voucher Package."
            )
        }
        .sheet(isPresented: $showingLoginView) {
            LoginView()
                .environmentObject(dataManager)
        }
    }
    
    /// 处理购买现金券套餐的逻辑
    private func handleBuyNowTap() {
        // 检查用户是否已登录
        if dataManager.currentUser == nil {
            showingLoginAlert = true
            return
        }
        
        // 检查购物车是否有其他商品（非Cash Voucher商品）
        let hasOtherItems = dataManager.cartItems.contains { cartItem in
            cartItem.menuItem.name != AppConfig.Cart.voucherPackageName
        }
        
        if hasOtherItems {
            // 如果有其他商品，显示清空购物车的提示
            showingClearCartAlert = true
            return
        }
        
        // 创建现金券套餐菜单项
        let voucherMenuItem = createVoucherPackageMenuItem()
        
        // 添加到购物车
        dataManager.addToCart(voucherMenuItem, quantity: 1)
        
        // 关闭当前页面
        dismiss()
        
        // 延迟后触发导航到购物车
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            navigateToCart = true
        }
    }
    
    /// 创建现金券套餐菜单项
    private func createVoucherPackageMenuItem() -> MenuItem {
        return MenuItem(
            name: AppConfig.Cart.cashVoucherPackageItem.name,
            englishName: AppConfig.Cart.cashVoucherPackageItem.name,
            description: AppConfig.Cart.cashVoucherPackageItem.nameChinese,
            englishDescription: AppConfig.Cart.cashVoucherPackageItem.description,
            price: AppConfig.Cart.cashVoucherPackageItem.price, // 使用配置的价格 S$300
            category: .promotion,
            imageName: "voucher_package",
            realImageName: nil,
            imageURL: nil,
            isAvailable: true,
            ingredients: [],
            availableMeatTypes: [],
            isSpicy: false,
            isVegetarian: true
        )
    }
    
    // MARK: - 顶部标题区域
    private var headerSection: some View {
        VStack(spacing: 8) {
            // 主标题
            Text(dataManager.currentLanguage == "zh" ? "现金礼券套餐" : "Cash Voucher Packages")
                .font(.system(size: 26, weight: .bold))
                .foregroundColor(.white)
                .multilineTextAlignment(.center)
                .shadow(color: Color.yellow.opacity(0.6), radius: 4, x: 0, y: 2)
                .padding(.top, 10)
        }
    }
    
    // MARK: - 礼券表格
    private var voucherTableSection: some View {
        VStack(spacing: 8) {
            // 表格标题
            HStack {
                Spacer()
                Text(dataManager.currentLanguage == "zh" ? "礼券套餐详情" : "Voucher Package Details")
                    .font(.system(size: 20, weight: .semibold))
                    .foregroundColor(.white)
                Spacer()
            }
            .padding(.top, 8)
            
            // 表格内容
            VStack(spacing: 8) {
                // 表头
                tableHeader
                
                // 礼券行
                voucherRow(
                    name: dataManager.currentLanguage == "zh" ? "礼券1" : "Package 1",
                    discount: dataManager.currentLanguage == "zh" ? "现金礼券 S$15 × 4 张" : "Cash Voucher S$15 × 4 pcs",
                    condition: dataManager.currentLanguage == "zh" ? "每张立减 S$15，最低消费 S$20" : "S$15 off per voucher, min. spend S$20"
                )
                
                voucherRow(
                    name: dataManager.currentLanguage == "zh" ? "礼券2" : "Package 2",
                    discount: dataManager.currentLanguage == "zh" ? "现金礼券 S$20 × 7 张" : "Cash Voucher S$20 × 7 pcs",
                    condition: dataManager.currentLanguage == "zh" ? "每张立减 S$20，最低消费 S$30" : "S$20 off per voucher, min. spend S$30"
                )
                
                voucherRow(
                    name: dataManager.currentLanguage == "zh" ? "礼券3" : "Package 3",
                    discount: dataManager.currentLanguage == "zh" ? "现金礼券 S$30 × 5 张" : "Cash Voucher S$30 × 5 pcs",
                    condition: dataManager.currentLanguage == "zh" ? "每张立减 S$30，最低消费 S$40" : "S$30 off per voucher, min. spend S$40"
                )
            }
            .background(
                RoundedRectangle(cornerRadius: 15)
                    .fill(Color.black.opacity(0.6))
                    .overlay(
                        RoundedRectangle(cornerRadius: 15)
                            .stroke(
                                LinearGradient(
                                    colors: [Color.yellow.opacity(0.6), Color.orange.opacity(0.4)],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                ),
                                lineWidth: 1
                            )
                    )
            )
            .padding(.horizontal, 4)
        }
    }
    
    // MARK: - 表格标题行
    private var tableHeader: some View {
        HStack(spacing: 8) {
            Text(dataManager.currentLanguage == "zh" ? "礼券名称" : "Package")
                .font(.system(size: 14, weight: .semibold))
                .foregroundColor(.yellow)
                .frame(maxWidth: .infinity, alignment: .leading)
            
            Text(dataManager.currentLanguage == "zh" ? "每张礼券优惠" : "Voucher Value")
                .font(.system(size: 14, weight: .semibold))
                .foregroundColor(.yellow)
                .frame(maxWidth: .infinity, alignment: .leading)
            
            Text(dataManager.currentLanguage == "zh" ? "使用条件（每单）" : "Usage Conditions")
                .font(.system(size: 14, weight: .semibold))
                .foregroundColor(.yellow)
                .frame(maxWidth: .infinity, alignment: .leading)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
    
    // MARK: - 礼券行
    private func voucherRow(name: String, discount: String, condition: String) -> some View {
        HStack(spacing: 8) {
            Text(name)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity, alignment: .leading)
            
            Text(discount)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity, alignment: .leading)
            
            Text(condition)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity, alignment: .leading)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 10)
    }
    
    // MARK: - 使用条件
    private var conditionsSection: some View {
        VStack(alignment: .leading, spacing: 8) {
            VStack(alignment: .leading, spacing: 8) {
                conditionItem(
                    title: dataManager.currentLanguage == "zh" ? "有效期：" : "Validity:",
                    content: dataManager.currentLanguage == "zh" ? "购买之日起一年内有效" : "Valid for one year from purchase date"
                )
                
                conditionItem(
                    title: dataManager.currentLanguage == "zh" ? "适用范围：" : "Applicable to:",
                    content: dataManager.currentLanguage == "zh" ? "所有菜品（酒水除外）" : "All dishes (beverages excluded)"
                )
                
                conditionItem(
                    title: dataManager.currentLanguage == "zh" ? "适用时间：" : "Operating hours:",
                    content: dataManager.currentLanguage == "zh" ? "周一至周五：11:00 am – 7:00 pm，周六 & 周日：11:00 am – 8:00 pm" : "Mon-Fri: 11:00 am – 7:00 pm, Sat & Sun: 11:00 am – 8:00 pm"
                )
                
                conditionItem(
                    title: dataManager.currentLanguage == "zh" ? "使用频率：" : "Usage limit:",
                    content: dataManager.currentLanguage == "zh" ? "每人每天限使用一次" : "One voucher per person per day"
                )
            }
            .padding(16)
            .background(
                RoundedRectangle(cornerRadius: 12)
                    .fill(Color.black.opacity(0.6))
                    .overlay(
                        RoundedRectangle(cornerRadius: 12)
                            .stroke(Color.yellow.opacity(0.3), lineWidth: 1)
                    )
            )
        }
    }
    
    // MARK: - 条件项
    private func conditionItem(title: String, content: String) -> some View {
        HStack(alignment: .top, spacing: 8) {
            Text(title)
                .font(.system(size: 14, weight: .semibold))
                .foregroundColor(.orange)
                .fixedSize(horizontal: true, vertical: false)
            
            Text(content)
                .font(.system(size: 14))
                .foregroundColor(.white)
                .multilineTextAlignment(.leading)
            
            Spacer()
        }
    }
    
    // MARK: - 条款说明
    private var termsSection: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Spacer()
                HStack {
                    Image(systemName: "checkmark.circle.fill")
                        .foregroundColor(.green)
                        .font(.system(size: 16))
                    
                    Text(dataManager.currentLanguage == "zh" ? "条款说明" : "Terms & Conditions")
                        .font(.system(size: 16, weight: .semibold))
                        .foregroundColor(Color(red: 0.4, green: 0.1, blue: 0.1))
                }
                Spacer()
            }
            .padding(.top, 8)
            
            VStack(alignment: .leading, spacing: 8) {
                termItem(
                    number: "1.",
                    content: dataManager.currentLanguage == "zh" ? "所有礼券不可在同一订单中叠加使用。" : "Vouchers cannot be combined in a single order."
                )
                
                termItem(
                    number: "2.",
                    content: dataManager.currentLanguage == "zh" ? "Cu Mr Bull Pte Ltd 保留对所有礼券条款与解释的最终权利。" : "Cu Mr Bull Pte Ltd reserves the final right to interpret all voucher terms."
                )
                
                termItem(
                    number: "3.",
                    content: dataManager.currentLanguage == "zh" ? "本公司保留在不提前通知的情况下，对礼券内容、积分规则及使用条件进行调整、替换或取消的权利，但所有调整将以不影响已购用户权益为前提。" : "The company reserves the right to adjust, replace or cancel voucher content without prior notice, provided that existing user rights are not affected."
                )
                
                termItem(
                    number: "4.",
                    content: dataManager.currentLanguage == "zh" ? "如用户已购买的礼券尚在有效期内，仍可在原约定条件下正常使用，不受新政策影响。" : "Purchased vouchers within validity period remain usable under original terms, unaffected by new policies."
                )
                
                termItem(
                    number: "5.",
                    content: dataManager.currentLanguage == "zh" ? "若因特殊情况需暂停某项优惠活动，本公司将通过 App、社交平台或店内公告提前说明。" : "If promotional activities need to be suspended due to special circumstances, advance notice will be given via App, social platforms or in-store announcements."
                )
            }
            .padding(16)
            .background(
                RoundedRectangle(cornerRadius: 12)
                    .fill(Color.black.opacity(0.6))
                    .overlay(
                        RoundedRectangle(cornerRadius: 12)
                            .stroke(Color.yellow.opacity(0.3), lineWidth: 1)
                    )
            )
        }
    }
    
    // MARK: - 条款项
    private func termItem(number: String, content: String) -> some View {
        HStack(alignment: .top, spacing: 8) {
            Text(number)
                .font(.system(size: 13, weight: .medium))
                .foregroundColor(.orange)
                .fixedSize()
            
            Text(content)
                .font(.system(size: 13))
                .foregroundColor(.white.opacity(0.9))
                .multilineTextAlignment(.leading)
                .lineLimit(nil)
            
            Spacer()
        }
    }
}

#Preview {
    VoucherDetailSheet()
        .environmentObject(DataManager.shared)
}